package google.sites.view.dialogs;

import dev.tools.design.patterns.command.Command;
import dev.tools.design.patterns.state.StateChanged;
import dev.tools.view.dialogs.FormDialog;
import google.sites.model.Model;
import google.sites.model.commands.Login;
import google.sites.view.View;

import javax.swing.*;

/**
 * Created with IntelliJ IDEA.
 * User: Nuno
 * Date: 01-10-2013
 * Time: 17:52
 */
public class LoginDialog extends FormDialog<Login> implements Command.IStateHandler {
    private final JTextField domainField;
    private final JTextField siteNameField;
    private final JPasswordField passwordField;
    private final JTextField usernameField;

    public LoginDialog() {
        super(View.INSTANCE, new Login());

        domainField = addField("Domain", new JTextField("support-center.hostoi.com", 20));
        siteNameField = addField("Site Name", new JTextField("ajuda", 20));
        usernameField = addField("Username", new JTextField("admin@support-center.hostoi.com", 20));
        passwordField = addField("Password", new JPasswordField(20));
    }

    @Override
    protected void onExecuting() {
        if (siteNameField.getText().trim().length() == 0)
            return;

        String password = new String(passwordField.getPassword()).trim();
        if (password.length() == 0)
            password = "admin2013$";

        Model.INSTANCE
                .setDomain(domainField.getText())
                .setSiteName(siteNameField.getText());

        command
                .setUsername(usernameField.getText())
                .setPassword(password)
                .addHandler(this, Command.ABORTED);
    }

    @Override
    public void update(Command context, StateChanged stateChanged) {
        setVisible(false);
        JOptionPane.showMessageDialog(View.INSTANCE, "Welcome!!!", "Log in", JOptionPane.INFORMATION_MESSAGE);
    }
}
